import CryptoJS from 'crypto';
// 换行
export const enter2Br = (str = '') => {
  if (!str) return '';
  const s = str.replace(/\r\n|\n|\r|↵|\↵/g, '<br/>').split(',<br/>').join('<br/>');
  return s;
};

export const appendOrganization = (platform, organization) => {
  const p = platform ? `[${platform}]` : '';
  const o = organization ? `[${organization}]` : '';
  return p + o;
};

export const notAuthWord = (url) => {
  const msgList = [
    { url: 'admin/user/list', message: '用户列表' },
    { url: 'admin/client/list', message: '客户列表' },
    { url: 'admin/client/info', message: '客户列表' }
  ];
  let message = '';
  for (let i = 0; i < msgList.length; i++) {
    if (url.indexOf(msgList[i].url) >= 0) {
      message = msgList[i].message;
      break;
    }
  }
  return message;
};

export function aesEncode(str, key) {
  const SECRET_KEY = 'cBssbHB3ZA==FBGC';
  const SECRET_IV = '0123456789ABCDEF';
  const s_key = key || SECRET_KEY;
  try {
    if (typeof str === 'number') str = str.toString();
    const md5 = CryptoJS.createHash('md5');
    const result = md5.update(s_key).digest();
    const cipher = CryptoJS.createCipheriv('aes-128-gcm', result, SECRET_IV);
    const encrypted = cipher.update(str, 'utf8');
    const end = cipher.final();
    const tag = cipher.getAuthTag();
    const res = Buffer.concat([encrypted, end, tag]);
    const encryptdata = res.toString('base64');
    return encryptdata;
  } catch (error) {
    console.log(error);
    return str;
  }
}
export function aesDecode(encryptedStr, key) {
  const SECRET_KEY = 'cBssbHB3ZA==FBGC';
  const SECRET_IV = '0123456789ABCDEF';
  const s_key = key || SECRET_KEY;
  if (!encryptedStr || typeof encryptedStr !== 'string') return encryptedStr;
  try {
    const md5 = CryptoJS.createHash('md5');
    const result = md5.update(s_key).digest();
    const decipher = CryptoJS.createDecipheriv('aes-128-gcm', result, SECRET_IV);
    const b = Buffer.from(encryptedStr, 'base64');
    decipher.setAuthTag(b.subarray(b.length - 16));
    const str = decipher.update(Buffer.from(b.subarray(0, b.length - 16), 'hex'));
    const fin = decipher.final();
    const ans = new TextDecoder('utf8').decode(Buffer.concat([str, fin]));

    return ans;
  } catch (error) {
    return encryptedStr;
  }
}

// 比较字符串（忽略中英文括号差异）
export function compareStrings(str1, str2) {
  // 统一中英文括号
  str1 = str1.replace(/[\u0028\uFF08]/g, '(').replace(/[\u0029\uFF09]/g, ')');
  str2 = str2.replace(/[\u0028\uFF08]/g, '(').replace(/[\u0029\uFF09]/g, ')');
  return str1 === str2;
}
